package com.upc.sealback.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.upc.sealback.bean.SealAntiFake;
import com.upc.sealback.config.ResponseResult;
import com.upc.sealback.service.SealConService;
import com.upc.sealback.service.SealDetailService;
import com.upc.sealback.service.SealUserService;
import com.upc.sealback.utils.BlindWatermark.BlindWatermark;
import com.upc.sealback.utils.BlindWatermark.Watermark;
import org.springframework.beans.factory.annotation.Autowired;
import com.upc.sealback.service.SealAntiFakeService;
import com.upc.sealback.mapper.SealAntiFakeMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
* @author zymac
* @description 针对表【seal_anti_fake(保存生成的防伪电子印章详情)】的数据库操作Service实现
* @createDate 2022-05-03 20:41:49
*/
@Service
public class SealAntiFakeServiceImpl extends ServiceImpl<SealAntiFakeMapper, SealAntiFake>
    implements SealAntiFakeService{
    @Autowired(required=false)
    SealAntiFakeMapper sealAntiFakeMapper;

    @Autowired
    SealDetailService sealDetailService;
    @Autowired
    SealConService sealConService;
    @Autowired
    SealUserService sealUserService;



    @Override
    public Integer addSealAntiFake(SealAntiFake sealAntiFake) {

        return sealAntiFakeMapper.addSealAntiFake(sealAntiFake);
    }

    /**
     * 导出防伪电子印章
     *
     * @param sealAntiFake
     * @return
     */
    @Override
    public ResponseResult<Object> exportAntiFakeSeal(SealAntiFake sealAntiFake) throws Exception {
        //按已生成的印章模板，从数据库中查找该模板的印章属性，以生成一个新的印章
        String sealId = sealAntiFake.getAntiFakeSealTemplateId();
        String fullPath = sealDetailService.getSealByTemplateSeal(sealId);

        // 下面开始为生成的印章加上盲水印
        // 谁在什么时候因为什么用了哪个印章
        // who when why what
        // 1、获取印章使用者（11位），作为盲水印的第一部分
        String mark1 = sealAntiFake.getAntiFakeUser();
        // 2、获取当前的时间戳（13位），作为盲水印第二部分
        String mark2 = String.valueOf(System.currentTimeMillis());
        // 3、获取任务的id（16位），作为盲水印的第三部分
        String mark3 = "";
        // 如果是签署文件，则加上签署文件信息，否则不加
        if(sealAntiFake.getAntiFakePurpose() == 1){
            mark3 = sealAntiFake.getAntiFakeSignId();
        }
        // 4、将生成的电子印章id作为盲水印的第四部分
        String antiFakeSealId = DigestUtils.md5DigestAsHex(mark2.getBytes(StandardCharsets.UTF_8)).substring(0,16);
        String mark4 = antiFakeSealId;
        // 四部分拼接，作为盲水印加到生成的印章中
        String watermark = mark1 + mark2 + mark3 + mark4;

        if(sealAntiFake.getAntiFakePassword() == null){
            sealAntiFake.setAntiFakePassword("1028");
        }
        //System.out.println(watermark);
        // 加盲水印
        Map<String,String> map = BlindWatermark.addWatermark(sealAntiFake.getAntiFakePassword(),fullPath,watermark,fullPath);
        // ResponseResult<Object> responseResult = Watermark.encodeWatermark(fullPath,watermark);
        // System.out.println(responseResult.getResult().toString());
        assert map != null;
        // 获取生成的印章的url
        String fileUrl = map.get("fileUrl");
        // 获取盲水印的大小 shape
        String size = map.get("size");

        // 获取模板印章使用次数并加一
        Integer useNum = sealConService.getSealById(sealId).getSealUseNum();
        Integer result = sealConService.updateSealUseNum(sealId,useNum+1);

        sealAntiFake.setAntiFakeSealId(antiFakeSealId);
        sealAntiFake.setAntiFakeSize(Integer.parseInt(size));
        sealAntiFake.setAntiFakePath(fileUrl);
        sealAntiFake.setAntiFakeTime(new Date(Long.parseLong(mark2)));
        sealAntiFake.setCreateTime(new Date());
        System.out.println(sealAntiFake);
        Integer addResult = sealAntiFakeMapper.addSealAntiFake(sealAntiFake);
        return ResponseResult.getSuccessResult(sealAntiFake.getAntiFakePath());
    }

    /**
     * 校验防伪电子印章
     *
     * @param sealAntiFake 盲水印信息
     * @return
     */
    @Override
    public ResponseResult<Object> checkAntiFakeSeal(SealAntiFake sealAntiFake) {
        String filePath = System.getProperty("user.dir") + "/src/main/resources/static" + sealAntiFake.getAntiFakePath();
        ResponseResult<Object> responseResult = BlindWatermark.decodeWatermark(sealAntiFake.getAntiFakePassword(),"318",filePath);
        assert responseResult != null;
        String result = responseResult.getResult().toString();
        String antiFakeUser = "";
        Date date = null;
        String antiFakeSealId = "";
        if(result.length() == 40){
            antiFakeUser = result.substring(0,11);
            long lt = new Long(result.substring(11,24));
            date = new Date(lt);
            antiFakeSealId = result.substring(24,40);
        }
        SealAntiFake sealAntiFake1 = sealAntiFakeMapper.getAntiFakeSealById(antiFakeSealId);
        if(sealAntiFake1 != null){
            if(!Objects.equals(sealAntiFake1.getAntiFakePassword(), sealAntiFake.getAntiFakePassword())){ // 密码不相等
                return ResponseResult.getSuccessResult("passwordError");
            }else if(!Objects.equals(sealAntiFake.getAntiFakeUser(),antiFakeUser)){ //用户名不相等
                return ResponseResult.getSuccessResult("userError");
            }
            String name = sealUserService.getUserByUserId(sealAntiFake1.getAntiFakeUser()).getUserName();
            sealAntiFake1.setAntiFakeUser(name);
            return ResponseResult.getSuccessResult(sealAntiFake1);
        }
        return ResponseResult.getSuccessResult("error");
    }

    /**
     * 根据模板印章id和使用用途获取使用列表
     *
     * @param page                   分页
     * @param antiFakeSealTemplateId 模板印章id
     * @param antiFakePurpose        使用用途
     * @return
     */
    @Override
    public List<SealAntiFake> getAntiFakeSealListByTemplateId(Page page, String antiFakeSealTemplateId, Integer antiFakePurpose) {
        return sealAntiFakeMapper.getAntiFakeSealListByTemplateId(page,antiFakeSealTemplateId,antiFakePurpose);
    }

    /**
     * 根据模板印章id和使用用途获取使用数量
     *
     * @param antiFakeSealTemplateId
     * @param antiFakePurpose
     * @return
     */
    @Override
    public Integer getAntiFakeSealNumByTemplateId(String antiFakeSealTemplateId, Integer antiFakePurpose) {
        return sealAntiFakeMapper.getAntiFakeSealNumByTemplateId(antiFakeSealTemplateId,antiFakePurpose);
    }

    /**
     * 根据签署人获取签署信息
     *
     * @param page
     * @param antiFakeUser
     * @return
     */
    @Override
    public List<SealAntiFake> getSignDetailByUser(Page page, String antiFakeUser,Integer antiFakePurpose) {
        List<SealAntiFake> sealAntiFakeList = sealAntiFakeMapper.getSignDetailByUser(page,antiFakeUser,antiFakePurpose);
        for (SealAntiFake sealAntiFake : sealAntiFakeList){
            sealAntiFake.setAntiFakeUser(sealUserService.getUserByUserId(sealAntiFake.getAntiFakeUser()).getUserName());
        }
        return sealAntiFakeList;
    }

    /**
     * 根据签署人获取签署信息数量
     *
     * @param antiFakeUser    用户
     * @param antiFakePurpose 用途
     * @return
     */
    @Override
    public Integer getSignDetailNumByUser(String antiFakeUser, Integer antiFakePurpose) {
        return sealAntiFakeMapper.getSignDetailNumByUser(antiFakeUser,antiFakePurpose);
    }

    /**
     * 根据id获取电子印章使用信息
     *
     * @param antiFakeSealId
     * @param antiFakePurpose
     * @return
     */
    @Override
    public SealAntiFake getAntiFakeDetail(String antiFakeSealId, Integer antiFakePurpose) {
        return sealAntiFakeMapper.getAntiFakeDetail(antiFakeSealId,antiFakePurpose);
    }
}




